package solution;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: tao
 * Date: 2023-11-23
 * Time: 13:08
 */
public class Solution {
    /**
     * 13. 罗马数字转整数
     * https://leetcode.cn/problems/roman-to-integer/description/
     * @param s
     * @return
     */
    public int romanToInt(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);

        int n = s.length();
        int result = 0;
        //遍历一遍s
        for(int i = 0; i < n; i++) {
            int value = map.get(s.charAt(i));
            //判断前后两个字符的值谁大，如果前面的大就正常加上对应的值，反之，则减小的那个值
            if(i < n - 1 && value < map.get(s.charAt(i + 1))) {
                result -= value;
            } else {
                result += value;
            }
        }
        return result;
    }
}
